package com.hxzy.controller.mobile.login;

import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.JwtTokenService;
import com.hxzy.common.util.MarketingThreadLocalUtil;
import com.hxzy.controller.mobile.login.req.MobileLoginReq;
import com.hxzy.controller.mobile.login.resp.MobileLoginResp;
import com.hxzy.controller.vue.login.req.AdminLoginReq;
import com.hxzy.controller.vue.login.resp.AdminLoginResp;
import com.hxzy.service.ContamerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @Author wy
 * @Description TODO
 * @Date 2023/9/27 14:01
 * @Version 1.0
 */
@RequestMapping(value = "/mobile")
@RestController
@Api(tags = "H5-登录")
public class MobileLoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtTokenService  mobileMultipleTokenService;

    @Autowired
    private ContamerService contamerService;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R<String> login(@RequestBody @Valid MobileLoginReq req){
        //验证码
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CAPTCHA_KEY,req.getUuid());
        Object redisValue=this.redisTemplate.opsForValue().get(redisKey);
        //从redis中移出验证码
        this.redisTemplate.delete(redisKey);

        //验证码不存在
        if(Objects.isNull(redisValue)){
            return R.build(AckCode.CODE_NOT_FOUND);
        }

        //验证码对不对
        if(!redisValue.toString().equalsIgnoreCase(req.getCode())){
            return R.build(AckCode.CODE_ERROR);
        }

        //走登录流程
        MobileLoginResp mobileLoginResp=this.contamerService.login(req);
        //存储到redis中，并生成jwt标识
        String jwtToken= mobileMultipleTokenService.createJwtToken(mobileLoginResp);

        return R.okHasData(jwtToken);
    }


    /**
     * 获取用户信息
     * @return
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping(value = "/user/info")
    public R<MobileLoginResp> userInfo(){
        MobileLoginResp loginResp = MarketingThreadLocalUtil.mobileThreadLocal.get();
        return R.okHasData(loginResp);
    }

    /**
     * 退出
     * @return
     */
    @ApiOperation(value = "退出")
    @PostMapping(value = "/logout")
    public R logout(){
        MobileLoginResp loginResp =MarketingThreadLocalUtil.mobileThreadLocal.get();
        this.mobileMultipleTokenService.delLoginUser(loginResp);
        return R.ok();
    }
}
